//
//  RBPickerVC.m
//  RBDemoProj
//
//  Created by Lan on 2019/1/3.
//  Copyright © 2019年 SummerTea. All rights reserved.
//

#import "RBPickerVC.h"
#import "RBDefine.h"
#import "UIViewController+RBAdd.h"
#import <UIView+YYAdd.h>

@interface RBPickerVC ()<UIPickerViewDataSource, UIPickerViewDelegate>

@property(nonatomic, strong)IBOutlet UIPickerView *pickerView;
@property(nonatomic, strong) NSArray *titles;
@property(nonatomic, copy) void (^block)(NSString *title, NSInteger index);

@end

@implementation RBPickerVC

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
}

#pragma mark - Private

- (void)setup
{
    self.contentView.width = kRBMainScreenWidth;
    self.contentView.height = self.contentView.height;
    self.contentView.left = 0;
    self.contentView.top = kRBMainScreenHeight;
    self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
}

#pragma mark - Public

- (void)showWithTitles: (NSArray *)titles
         selectedIndex: (NSInteger)selectedIndex
                fromVc: (UIViewController *)fromVc
            completion: (void(^)(NSString *title, NSInteger index))block;
{
    self.titles = titles;
    self.block = block;
    [self.view addSubview:self.contentView];
    [fromVc presentVc:self];
    [self.pickerView selectRow:selectedIndex inComponent:0 animated:NO];
}

- (void)show
{
    [UIView animateWithDuration:0.05 animations:^{
        self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            self.contentView.bottom = kRBMainScreenHeight - kRBSafeBottomHeight;
        }];
    }];
}

- (void)dismiss
{
    [UIView animateWithDuration:0.15 animations:^{
        self.contentView.top = kRBMainScreenHeight;
    }];
    [UIView animateWithDuration:0.05 delay:0.1 options:0 animations:^{
        self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }];
}

#pragma mark - UIPickerViewDataSource & Delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return self.titles.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return self.titles[row];
}

#pragma mark - Event

- (IBAction)cancelBtnTapped:(id)sender
{
    [self dismiss];
}

- (IBAction)confirmBtnTapped:(id)sender
{
    if (self.block)
    {
        NSInteger index = [self.pickerView selectedRowInComponent:0];
        self.block(self.titles[index], index);
    }
    [self dismiss];
}

#pragma mark - Getter

@end
